Page({
  data: {
    form: { semester: "", gpa: "", totalCredits: "", courses: [] },
  },

  onLoad(options) {
    try {
      if (options && options.data) {
        const t = JSON.parse(decodeURIComponent(options.data));
        // 确保课程数据中的学分字段正确映射
        if (t.courses) {
          t.courses = t.courses.map((course) => ({
            ...course,
            credit: course.credit || course.credits || "0", // 确保credit字段有值
            score: course.score || "0", // 确保score字段有值
          }));
        }
        this.setData({ form: t });
      } else {
        const local = require("../../../../utils/local");
        const t = local.getTranscript();
        if (t) {
          // 确保课程数据中的学分字段正确映射
          if (t.courses) {
            t.courses = t.courses.map((course) => ({
              ...course,
              credit: course.credit || course.credits || "0", // 确保credit字段有值
              score: course.score || "0", // 确保score字段有值
            }));
          }
          this.setData({ form: t });
        }
      }
    } catch (error) {
      console.error("加载成绩单数据失败:", error);
    }
  },

  onSemester(e) {
    this.setData({ "form.semester": e.detail.value });
  },
  onGpa(e) {
    this.setData({ "form.gpa": e.detail.value });
  },
  onCredits(e) {
    this.setData({ "form.totalCredits": e.detail.value });
  },
  onCourseInput(e) {
    const { index, field } = e.currentTarget.dataset;
    const value = e.detail.value;
    const key = `form.courses[${index}].${field}`;
    this.setData({ [key]: value });
  },
  addCourse() {
    const list = this.data.form.courses || [];
    list.push({
      name: "",
      type: "", // 添加课程类型字段
      credit: "0", // 设置默认学分为0而不是空字符串
      score: "0", // 设置默认成绩为0而不是空字符串
      semester: this.data.form.semester || "",
    });
    this.setData({ "form.courses": list });
  },
  removeCourse(e) {
    const { index } = e.currentTarget.dataset;
    const list = (this.data.form.courses || []).slice();
    if (index >= 0 && index < list.length) {
      list.splice(index, 1);
      this.setData({ "form.courses": list });
    }
  },
  save() {
    const local = require("../../../../utils/local");
    const f = this.data.form;
    const normalized = {
      semester: f.semester,
      gpa: parseFloat(f.gpa) || 0,
      totalCredits: parseFloat(f.totalCredits) || 0,
      courses: (f.courses || []).map((c) => ({
        name: c.name,
        credit: parseFloat(c.credit) || 0,
        score: parseFloat(c.score) || 0,
        semester: c.semester || f.semester,
        type: c.type || "", // 保留课程类型信息
      })),
      imageUrl: "",
      verified: false,
    };
    const res = local.saveTranscript(normalized);
    if (res.success) {
      wx.showToast({ title: "已保存", icon: "success" });
      setTimeout(() => wx.navigateBack(), 500);
    }
  },
});
